import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Switch, message, Popconfirm } from 'antd';
import ProTable from '@ant-design/pro-table';
import { getCleaningSettings, createCleaningSetting, updateCleaningSetting, deleteCleaningSetting } from '@/services/cleaning';
import { getStores } from '@/services/store';
import SettingForm from './components/SettingForm';

const CleaningSetting = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [stores, setStores] = useState([]);
  const actionRef = useRef();

  useEffect(() => {
    fetchStores();
  }, []);

  const fetchStores = async () => {
    try {
      const res = await getStores({ page_size: 999 });
      if (res.success) {
        setStores(res.data.list);
      } else {
        message.error('获取门店列表失败');
      }
    } catch (error) {
      message.error('获取门店列表失败');
    }
  };

  const handleAdd = () => {
    setCurrentRow(null);
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setCurrentRow(record);
    setModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const res = await deleteCleaningSetting(id);
      if (res.success) {
        message.success('删除成功');
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.msg || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleFormSubmit = async (values) => {
    const isUpdate = currentRow && currentRow.id;
    try {
      let res;
      if (isUpdate) {
        res = await updateCleaningSetting(currentRow.id, values);
      } else {
        res = await createCleaningSetting(values);
      }

      if (res.success) {
        message.success(isUpdate ? '更新成功' : '创建成功');
        setModalVisible(false);
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(res.msg || (isUpdate ? '更新失败' : '创建失败'));
      }
    } catch (error) {
      message.error(isUpdate ? '更新失败' : '创建失败');
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id',
      search: false, },
        {
      title: '门店名称',
      dataIndex: 'store_id',
      key: 'store_id',
      render: (_, record) => stores.map((store) => store.id==record.store_id?store.name:''),
      valueType: 'select',
      valueEnum: stores.reduce((acc, cur) => {
        acc[cur.id] = { text: cur.name };
        return acc;
      }, {}),
    },
    {
      title: '启用状态',
      dataIndex: 'enabled',
      key: 'enabled',
      search: false,
      render: (text) => <Switch checked={text} disabled />,
    },
    { title: '预留保洁时间（分钟）', dataIndex: 'reserved_minutes', key: 'reserved_minutes',search:false },
    {
      title: '操作',
      key: 'action',
      search: false,
      render: (_, record) => (
        <>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="保洁设置列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" key="primary" onClick={handleAdd}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          const res = await getCleaningSettings({ ...params, page: params.current, page_size: params.pageSize });
          if (res.success) {
            return {
              data: res.data.list,
              success: true,
              total: res.data.total,
            };
          }
          return { data: [], success: false };
        }}
        columns={columns}
      />
      <SettingForm
        visible={modalVisible}
        onCancel={() => setModalVisible(false)}
        onSubmit={handleFormSubmit}
        initialValues={currentRow}
        stores={stores}
      />
    </PageContainer>
  );
};

export default CleaningSetting;